"""
The MIT License (MIT)
Copyright © 2020 Walkline Wang (https://walkline.wang)
https://gitee.com/walkline/MicroPython-with-Aligenie-Voice-Skill
"""
import json
import utime
from config import Config


class Aligenie(object):
	__RETURN_DATA = {
		"returnCode": "0",
		"returnErrorSolution": "",
		"returnMessage": "",
		"returnValue": {
			"reply": "",
			"resultType": "RESULT",
			"executeCode": "SUCCESS",
			"msgInfo": ""
		}
	}

	def __init__(self, post_data):
		self.__request_city = None
		self.__device_id = None
		self.__slot_location = None
		self.__slot_date = None
		self.__slot_computer = None
		self.__slot_onoff = None

		if isinstance(post_data, bytes):
			post_data = json.loads(post_data)

		self.__utterance = post_data['utterance']
		self.__skill_name = post_data['skillName']
		self.__intent_name = post_data['intentName']

		try:
			self.__request_city = post_data['requestData']['city']
		except KeyError:
			pass

		try:
			self.__device_id = post_data['requestData']['deviceOpenId'].split('/')[0]
		except KeyError:
			pass

		try:
			slots = post_data['slotEntities']

			for slot in slots:
				intentParameterName = slot['intentParameterName']

				if intentParameterName.startswith(Config.ENTITY_SYS_LOCATION):
					self.__slot_location = slot['slotValue']
				elif intentParameterName.startswith(Config.ENTITY_SYS_DATE):
					if slot['slotValue'] == "今天":
						self.__slot_date = "%02d-%02d-%02d" % (utime.localtime()[:3])
					else:
						self.__slot_date = json.loads(slot['slotValue'])['iDateString']
				elif intentParameterName.startswith(Config.ENTITY_COMPUTER):
					self.__slot_computer = slot['slotValue']
				elif intentParameterName.startswith(Config.ENTITY_ONOFF):
					self.__slot_onoff = slot['slotValue']
		except KeyError:
			pass

	@property
	def utterance(self):
		return self.__utterance
	
	@property
	def skill_name(self):
		return self.__skill_name
	
	@property
	def intent_name(self):
		return self.__intent_name
	
	@property
	def device_id(self):
		return self.__device_id

	@property
	def request_city(self):
		return self.__request_city
	
	@property
	def location(self):
		return self.__slot_location

	@property
	def city(self):
		return self.__slot_location if self.__slot_location is not None else self.__request_city if self.__request_city is not None else "无"
	
	@property
	def computer(self):
		return self.__slot_computer
	
	@property
	def onoff(self):
		return self.__slot_onoff

	@property
	def date(self):
		return self.__slot_date

	@property
	def reply(self):
		return self.__RETURN_DATA['returnValue']['reply']
	
	@reply.setter
	def reply(self, value):
		self.__RETURN_DATA['returnValue']['reply'] = value

	@property
	def response(self):
		return self.__RETURN_DATA
